<template>
  <div class="app-container">
    <el-card class="search-wrapper">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item>
          <el-input
            v-model="queryParams.card_no"
            placeholder="黑卡号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="queryParams.org_name"
            placeholder="企业名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="queryParams.user_name"
            placeholder="用户姓名"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.type" placeholder="卡片类型" clearable>
            <el-option label="机构卡" value="organization" />
            <el-option label="个人卡" value="personal" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryParams.status" placeholder="状态" clearable>
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="handleAdd">新增黑卡</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-wrapper">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
      >
        <el-table-column prop="card_no" label="黑卡号" width="180" />
        <el-table-column label="卡片类型" width="100">
          <template #default="scope">
            {{ scope.row.card_type === 'organization' ? '机构卡' : '个人卡' }}
          </template>
        </el-table-column>
        <el-table-column label="所属企业/用户" width="180">
          <template #default="scope">
            <template v-if="scope.row.card_type === 'organization'">
              <el-tooltip
                v-if="scope.row.org_name"
                :content="scope.row.org_name"
                placement="top"
              >
                <span>{{ scope.row.org_name }}</span>
              </el-tooltip>
              <span v-else>-</span>
            </template>
            <template v-else>
              <el-tooltip
                v-if="scope.row.user_name"
                :content="scope.row.user_name"
                placement="top"
              >
                <span>{{ scope.row.user_name }}</span>
              </el-tooltip>
              <span v-else>-</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="balance" label="总额度" width="120">
          <template #default="scope">
            {{ formatAmount(scope.row.balance) }}
          </template>
        </el-table-column>
        <el-table-column prop="available_balance" label="可用额度" width="120">
          <template #default="scope">
            {{ formatAmount(scope.row.available_balance) }}
          </template>
        </el-table-column>
        <el-table-column prop="frozen_balance" label="冻结额度" width="120">
          <template #default="scope">
            {{ formatAmount(scope.row.frozen_balance) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              type="primary"
              link
              @click="handleRecharge(scope.row)"
            >
              充值
            </el-button>
            <el-button
              :type="scope.row.status ? 'danger' : 'success'"
              link
              @click="handleStatus(scope.row)"
            >
              {{ scope.row.status ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.limit"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 表单弹窗 -->
    <card-form
      v-model:visible="formVisible"
      :card-id="currentId"
      @success="handleSuccess"
    />

    <!-- 充值弹窗 -->
    <recharge-form
      v-model:visible="rechargeVisible"
      :card-info="currentCard"
      @success="handleRechargeSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import CardForm from './Form.vue'
import RechargeForm from './RechargeForm.vue'
import { useRouter } from 'vue-router'

// 获取 router 实例
const router = useRouter()

// 查询参数
const queryParams = reactive({
  page: 1,
  limit: 10,
  card_no: '',
  org_name: '',
  user_name: '',
  type: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

// 表单弹窗控制
const formVisible = ref(false)
const rechargeVisible = ref(false)
const currentId = ref(null)
const currentCard = ref(null)

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    const res = await request.get('/black-card/list', {
      params: {
        params: {
          page: queryParams.page,
          limit: queryParams.limit,
          keyword: queryParams.card_no,
          org_name: queryParams.org_name,
          user_name: queryParams.user_name,
          type: queryParams.type,
          status: queryParams.status
        }
      }
    })
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取列表失败：', error)
  }
  loading.value = false
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.card_no = ''
  queryParams.org_name = ''
  queryParams.user_name = ''
  queryParams.type = ''
  queryParams.status = ''
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  queryParams.limit = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.page = val
  getList()
}

// 新增
const handleAdd = () => {
  currentId.value = null
  formVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  currentId.value = row.card_id
  formVisible.value = true
}

// 详情
const handleDetail = (row) => {
  // 跳转到详情页面
  const { href } = router.resolve({
    name: 'BlackCardDetail',
    query: { id: row.card_id }
  })
  window.open(href, '_blank')
}

// 充值
const handleRecharge = (row) => {
  currentCard.value = row
  rechargeVisible.value = true
}

// 充值成功回调
const handleRechargeSuccess = () => {
  rechargeVisible.value = false
  router.push({ name: 'RechargeList' })
}

// 更改状态
const handleStatus = (row) => {
  const statusText = row.status ? '禁用' : '启用'
  ElMessageBox.confirm(
    `确认要${statusText}该黑卡吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await request.post('/black-card/update-status', {
        params: { id: row.card_id },
        status: row.status ? 0 : 1
      })
      ElMessage.success(res.message)
      getList()
    } catch (error) {
      console.error('更改状态失败：', error)
    }
  }).catch(() => {})
}

// 操作成功
const handleSuccess = () => {
  getList()
}

// 格式化金额
const formatAmount = (amount) => {
  if (!amount && amount !== 0) return '--'
  return Number(amount).toFixed(2)
}

// 初始化
getList()
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-wrapper {
    margin-bottom: 20px;
  }
  
  .table-wrapper {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}
</style> 